﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.Model;
using FlyHorse.LIMS.WinApp.Utils;
using FlyHorse.LIMS.WinApp.XtraReportTemplate;
using DevExpress.XtraReports.UI;
using DevExpress.LookAndFeel;
using FlyHorse.LIMS.WinApp.LanguageResource;
using System.Data.Entity;
using DevExpress.XtraGrid;
using DevExpress.XtraPrinting;
using System.Drawing.Printing;

namespace FlyHorse.LIMS.WinApp.DataManageForms.ReportProductForms
{
    public partial class ReportProductMainForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.GoodBll goodsBll = new BLL.GoodBll();
        BLL.ReportProductBll reportProductBll = new BLL.ReportProductBll();
        BLL.ToolBll toolBll = new BLL.ToolBll();
        IQueryable<ReportProduct> _models;
        public ReportProductMainForm()
        {
            InitializeComponent();
        }
        private void ReportProductMainForm_Load(object sender, EventArgs e)
        {
            CheckAuthority();
            this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            this.gridView1.OptionsBehavior.Editable = false;
            this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
            this.gridView2.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            this.gridView2.OptionsBehavior.Editable = false;
            this.gridView2.OptionsSelection.EnableAppearanceFocusedCell = false;


            //绑定物料名称
            var goodsList = goodsBll.GetRawGoodList();
            searchLookUpEdit_Goods.Properties.DataSource = goodsBll.GetProductGoodList();
            searchLookUpEdit_Customer.Properties.DataSource = toolBll.GetCustomerList();


            repositoryItemLookUpEdit1.DataSource = toolBll.GetAllGoodList();
            repositoryItemLookUpEdit2.DataSource = toolBll.GetAllLoginUersList();
            repositoryItemLookUpEdit3.DataSource = toolBll.GetCustomerList();
            //repositoryItemLookUpEdit4.DataSource = toolBll.GetTestItemList();

            var models = reportProductBll.LoadEntitiesAsNoTracking(m => true);
            _models = models;
            InitGrid(_models);

        }

        private void InitGrid(IQueryable<ReportProduct> models)
        {
            models = models.OrderByDescending(m => m.AddDateTime);
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            int pageSize = 0;
            try
            {
                pageSize = Convert.ToInt32(this.barEditItem_pageSize.EditValue);
            }
            catch (Exception)
            {
                XtraMessageBox.Show(ResourceOverall.TotalPageErr);
                return;
            }
            if (pageSize == 0)
            {
                barEditItem_pageSize.EditValue = 30;
                pageSize = 30;
            }
            splashScreenManager1.ShowWaitForm();
            //...?

            PagedList<ReportProduct> pagedList = new PagedList<ReportProduct>(models, pageIndex, pageSize);

            this.barStaticItem_pageIndex.Caption = pagedList.PageIndex.ToString();
            this.barStaticItem_totalPage.Caption = pagedList.TotalPages.ToString();
            this.barEditItem_pageSize.Caption = pagedList.PageSize.ToString();

            this.gridControl1.DataSource = Utils.TransformReport.TransformProductReport(pagedList);

            //排序
            gridView2.BeginDataUpdate();
            try
            {
                gridView2.ClearSorting();
                gridView2.Columns["FormOrder"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
            }
            finally
            {
                gridView2.EndDataUpdate();
            }
            splashScreenManager1.CloseWaitForm();
        }

        private void ButtonItem_Add_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ReportProductDetailForm reportProductDetailForm = new ReportProductDetailForm(ShowAllData);
            reportProductDetailForm.Show();
        }

        private void ButtonItem_Edit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string reportID = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportProductID"));
            ReportProduct report = reportProductBll.LoadEntities(m => m.ReportProductID == reportID).First();
            ReportProductDetailForm form = new ReportProductDetailForm(report, RefreshGrid);
            form.Show();

        }

        private void ButtonItem_Delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (OJCB4Entities db = new OJCB4Entities())
            {
                string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportProductID"));
                ReportProduct report = db.ReportProducts.Where(m => m.ReportProductID == id).First();
                if (report != null)
                {
                    DialogResult result = XtraMessageBox.Show(ResourceOverall.ConfirmDelete, ResourceOverall.SystemWarningStr, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {
                        db.ReportProducts.Remove(report);
                        bool res = db.SaveChanges() > 0;
                        if (res)
                        {
                            InitGrid(_models);
                            XtraMessageBox.Show(ResourceOverall.DeleteSucceed);
                        }
                    }
                }
            }
        }

        private void ButtonItem_Print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            #region 未多选打印前的代码
            string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportProductID"));
            ReportProduct ReportProduct = reportProductBll.LoadEntities(m => m.ReportProductID == id).First();
            if (ReportProduct == null)
            {
                XtraMessageBox.Show("没有选中任何记录！");
                return;
            }
            XtraReportProduct report = new XtraReportProduct(ReportProduct);

            using (ReportPrintTool printTool = new ReportPrintTool(report))
            {
                // Invoke the Ribbon Print Preview form modally, 
                // and load the report document into it.
                printTool.ShowRibbonPreviewDialog();

                // Invoke the Ribbon Print Preview form
                // with the specified look and feel setting.
                printTool.ShowRibbonPreview(UserLookAndFeel.Default);
            }
            #endregion

            #region 多选打印代码

            //int selectCount = gridView1.SelectedRowsCount;
            //if (selectCount == 0)
            //{
            //    XtraMessageBox.Show(ResourceOverall.SelectNull);
            //    return;
            //}
            //int[] selectRows = gridView1.GetSelectedRows();

            //DialogResult result = XtraMessageBox.Show(ResourceOverall.ConfirmDelete, ResourceOverall.SystemWarningStr, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            //if (result == DialogResult.OK)
            //{
            //    object sourse = this.gridControl1.DataSource;
            //    List<ReportProduct> dataSourse = (List<ReportProduct>)sourse;
            //    List<ReportProduct> delList = new List<ReportProduct>();

            //    for (int i = 0; i < selectRows.Length; i++)
            //    {
            //        int row = selectRows[i];
            //        int dataRowIndex = this.gridView1.GetDataSourceRowIndex(row);
            //        ReportProduct standard = dataSourse[dataRowIndex];
            //        delList.Add(standard);
            //    }

            //    foreach (var item in delList)
            //    {
            //        XtraReportProduct xtraReportProduct = new XtraReportProduct(item);
            //        using (ReportPrintTool printTool = new ReportPrintTool(report))
            //        {
            //            // Invoke the Ribbon Print Preview form modally, 
            //            // and load the report document into it.
            //            printTool.ShowRibbonPreviewDialog();

            //            // Invoke the Ribbon Print Preview form
            //            // with the specified look and feel setting.
            //            printTool.ShowRibbonPreview(UserLookAndFeel.Default);
            //        }
            //    }
            //}
            #endregion


        }

        private void simpleButton_search_Click(object sender, EventArgs e)
        {
            var models = reportProductBll.LoadEntitiesAsNoTracking(m => true);
            if (searchLookUpEdit_Goods.EditValue != null)
            {
                string goodsID = Convert.ToString(searchLookUpEdit_Goods.EditValue);
                models = models.Where(m => m.GoodsID == goodsID);
            }
            if (searchLookUpEdit_Customer.EditValue != null)
            {
                string custID = Convert.ToString(this.searchLookUpEdit_Customer.EditValue);
                models = models.Where(m => m.CustomerID == custID);
            }
            if (this.dateEdit_start.Text != "" && this.dateEdit_start.EditValue != null)
            {
                models = models.Where(m => m.DateProduced >= this.dateEdit_start.DateTime);
            }
            if (this.dateEdit_endDate.Text != "" && this.dateEdit_endDate.EditValue != null)
            {
                models = models.Where(m => m.DateProduced <= this.dateEdit_endDate.DateTime);
            }
            _models = models;
            InitGrid(_models);
        }

        private void simpleButton_clear_Click(object sender, EventArgs e)
        {
            ShowAllData();
        }

        private void ShowAllData()
        {
            this.searchLookUpEdit_Goods.EditValue = null;
            this.searchLookUpEdit_Customer.EditValue = null;
            this.dateEdit_start.EditValue = null;
            this.dateEdit_endDate.EditValue = null;

            var models = reportProductBll.LoadEntities(m => true);
            _models = models;
            InitGrid(_models);
        }

        private void RefreshGrid()
        {
            InitGrid(_models);
        }



        private void CheckAuthority()
        {
            List<Resource> resList = LoginUserUtil.LoginUser.Role.Resources.ToList();
            if (resList.Where(m => m.ResourceKey == "ProductReportButtonItem_Add").Count() != 1)
            {
                ButtonItem_Add.Enabled = false;
            }
            if (resList.Where(m => m.ResourceKey == "ProductReportButtonItem_Edit").Count() != 1)
            {
                ButtonItem_Edit.Enabled = false;
            }
            if (resList.Where(m => m.ResourceKey == "ProductReportButtonItem_Delete").Count() != 1)
            {
                ButtonItem_Delete.Enabled = false;
            }
            if (resList.Where(m => m.ResourceKey == "ProductReportButtonItem_Print").Count() != 1)
            {
                ButtonItem_Print.Enabled = false;
            }
            if (resList.Where(m => m.ResourceKey == "ProductReportButtonItem_PrintAll").Count() != 1)
            {
                ButtonItem_PrintAll.Enabled = false;
            }
        }

        private void ButtonItem_PrintAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //ShowGridPreview(this.gridControl1);
            PreviewPrintableComponent(gridControl1, gridControl1.LookAndFeel);
        }


        //private void ShowGridPreview(GridControl grid)
        //{
        //    // Check whether the GridControl can be previewed.
        //    if (!grid.IsPrintingAvailable)
        //    {
        //        MessageBox.Show("The 'DevExpress.XtraPrinting' library is not found", "Error");
        //        return;
        //    }

        //    // Open the Preview window.
        //    grid.ShowPrintPreview();

        //}

        //private void PrintGrid(GridControl grid)
        //{
        //    // Check whether the GridControl can be printed.
        //    if (!grid.IsPrintingAvailable)
        //    {
        //        MessageBox.Show("The 'DevExpress.XtraPrinting' library is not found", "Error");
        //        return;
        //    }

        //    // Print.
        //    grid.Print();
        //}

        private void PreviewPrintableComponent(IPrintable component, UserLookAndFeel lookAndFeel)
        {
            // Create a link that will print a control.?
            PrintableComponentLink link = new PrintableComponentLink()
            {
                PrintingSystemBase = new PrintingSystemBase(),
                Component = component,
                Landscape = true,
                PaperKind = PaperKind.A2,
                //Margins = new Margins(20, 20, 20, 20)
            };
            // Show the report.?
            link.ShowRibbonPreview(lookAndFeel);
        }

        private void barButton_firstPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.barStaticItem_pageIndex.Caption = "1";
            InitGrid(_models);
        }

        private void barButton_previousPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            if (pageIndex >= 1)
            {
                this.barStaticItem_pageIndex.Caption = (pageIndex - 1).ToString();
                InitGrid(_models);
            }
        }

        private void barButton_nextPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            int totalPage = Convert.ToInt32(barStaticItem_totalPage.Caption);
            if (pageIndex < totalPage)
            {
                this.barStaticItem_pageIndex.Caption = (pageIndex + 1).ToString();
                InitGrid(_models);
            }
        }

        private void barButton_lastPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            int totalPage = Convert.ToInt32(barStaticItem_totalPage.Caption);
            if (pageIndex < totalPage)
            {
                this.barStaticItem_pageIndex.Caption = totalPage.ToString();
                InitGrid(_models);
            }
        }

        private void barEditItem_pageSize_EditValueChanged(object sender, EventArgs e)
        {
            InitGrid(_models);
        }

        //private void gridControl1_Load(object sender, EventArgs e)
        //{
        //    PreviewPrintableComponent(gridControl1, gridControl1.LookAndFeel);
        //}






    }
}